<template>
  <div class="store-settings-page">
    <div class="page-header">
      <h1>Store Settings</h1>
    </div>

    <el-card v-loading="loading">
      <el-form
        ref="formRef"
        :model="formData"
        label-width="180px"
      >
        <el-divider content-position="left">
          <h3>Basic Information</h3>
        </el-divider>

        <el-form-item label="Site Name">
          <el-input v-model="formData.site_name" placeholder="Lucy African Fashion" />
        </el-form-item>

        <el-form-item label="Site Description">
          <el-input
            v-model="formData.site_description"
            type="textarea"
            :rows="2"
            placeholder="Your trusted African Wear Supplier from China"
          />
        </el-form-item>

        <el-form-item label="Welcome Text">
          <el-input
            v-model="formData.welcome_text"
            type="textarea"
            :rows="2"
          />
        </el-form-item>

        <el-form-item label="About Text">
          <el-input
            v-model="formData.about_text"
            type="textarea"
            :rows="4"
          />
        </el-form-item>

        <el-divider content-position="left">
          <h3>Contact Information</h3>
        </el-divider>

        <el-form-item label="Address">
          <el-input v-model="formData.address" />
        </el-form-item>

        <el-form-item label="WhatsApp">
          <el-input v-model="formData.whatsapp" placeholder="+86 123 4567 8900" />
        </el-form-item>

        <el-form-item label="WeChat ID">
          <el-input v-model="formData.wechat" placeholder="lucyfashion" />
        </el-form-item>

        <el-form-item label="Instagram">
          <el-input v-model="formData.instagram" placeholder="@lucyafricanfashion" />
        </el-form-item>

        <el-form-item label="Email">
          <el-input v-model="formData.email" placeholder="contact@lucyfashion.com" />
        </el-form-item>

        <el-form-item label="Phone">
          <el-input v-model="formData.phone" placeholder="+86 123 4567 8900" />
        </el-form-item>

        <el-form-item label="Shipping Info">
          <el-input
            v-model="formData.shipping_info"
            type="textarea"
            :rows="2"
          />
        </el-form-item>

        <el-divider content-position="left">
          <h3>Images</h3>
        </el-divider>

        <el-form-item label="Logo">
          <div class="image-upload-section">
            <el-image
              v-if="formData.logo"
              :src="formData.logo"
              fit="contain"
              style="width: 200px; height: 100px; margin-bottom: 1rem;"
            />
            <el-upload
              :file-list="logoFileList"
              :on-change="(file) => handleImageChange(file, 'logo')"
              :before-upload="() => false"
              :limit="1"
              accept="image/*"
              list-type="picture"
            >
              <el-button size="small">Upload Logo</el-button>
            </el-upload>
          </div>
        </el-form-item>

        <el-form-item label="Banner">
          <div class="image-upload-section">
            <el-image
              v-if="formData.banner"
              :src="formData.banner"
              fit="cover"
              style="width: 100%; max-width: 600px; height: 200px; margin-bottom: 1rem;"
            />
            <el-upload
              :file-list="bannerFileList"
              :on-change="(file) => handleImageChange(file, 'banner')"
              :before-upload="() => false"
              :limit="1"
              accept="image/*"
              list-type="picture"
            >
              <el-button size="small">Upload Banner</el-button>
            </el-upload>
          </div>
        </el-form-item>

        <el-form-item label="WeChat QR Code">
          <div class="image-upload-section">
            <el-image
              v-if="formData.wechat_qr"
              :src="formData.wechat_qr"
              fit="contain"
              style="width: 200px; height: 200px; margin-bottom: 1rem;"
            />
            <el-upload
              :file-list="wechatQrFileList"
              :on-change="(file) => handleImageChange(file, 'wechat_qr')"
              :before-upload="() => false"
              :limit="1"
              accept="image/*"
              list-type="picture"
            >
              <el-button size="small">Upload QR Code</el-button>
            </el-upload>
          </div>
        </el-form-item>

        <el-form-item label="Store Images">
          <div class="image-upload-section">
            <div v-if="storeImages.length" class="store-images-grid">
              <el-image
                v-for="(img, index) in storeImages"
                :key="index"
                :src="img"
                fit="cover"
                style="width: 150px; height: 150px;"
              />
            </div>
            <el-upload
              :file-list="storeImagesFileList"
              :on-change="handleStoreImagesChange"
              :on-remove="handleStoreImageRemove"
              :before-upload="() => false"
              multiple
              accept="image/*"
              list-type="picture"
            >
              <el-button size="small">Upload Store Images</el-button>
            </el-upload>
          </div>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm" :loading="submitting" size="large">
            Save Settings
          </el-button>
          <el-button @click="loadStoreInfo" size="large">Reset</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { storeAPI } from '@/api'

const loading = ref(false)
const submitting = ref(false)
const formRef = ref(null)

const formData = reactive({
  site_name: '',
  site_description: '',
  welcome_text: '',
  about_text: '',
  address: '',
  whatsapp: '',
  wechat: '',
  instagram: '',
  email: '',
  phone: '',
  shipping_info: '',
  logo: '',
  banner: '',
  wechat_qr: '',
  store_images: []
})

const logoFileList = ref([])
const bannerFileList = ref([])
const wechatQrFileList = ref([])
const storeImagesFileList = ref([])

const newLogo = ref(null)
const newBanner = ref(null)
const newWechatQr = ref(null)
const newStoreImages = ref([])

const storeImages = computed(() => {
  try {
    return typeof formData.store_images === 'string' 
      ? JSON.parse(formData.store_images) 
      : formData.store_images || []
  } catch {
    return []
  }
})

const loadStoreInfo = async () => {
  try {
    loading.value = true
    const response = await storeAPI.getInfo()
    if (response.success) {
      Object.assign(formData, response.data)
    }
  } catch (error) {
    console.error('Failed to load store info:', error)
  } finally {
    loading.value = false
  }
}

const handleImageChange = (file, field) => {
  if (field === 'logo') {
    logoFileList.value = [file]
    newLogo.value = file.raw
  } else if (field === 'banner') {
    bannerFileList.value = [file]
    newBanner.value = file.raw
  } else if (field === 'wechat_qr') {
    wechatQrFileList.value = [file]
    newWechatQr.value = file.raw
  }
}

const handleStoreImagesChange = (file, fileList) => {
  storeImagesFileList.value = fileList
  newStoreImages.value = fileList.map(f => f.raw).filter(Boolean)
}

const handleStoreImageRemove = (file, fileList) => {
  storeImagesFileList.value = fileList
  newStoreImages.value = fileList.map(f => f.raw).filter(Boolean)
}

const submitForm = async () => {
  try {
    submitting.value = true

    const formDataToSend = new FormData()

    // Add text fields
    Object.keys(formData).forEach(key => {
      if (key !== 'logo' && key !== 'banner' && key !== 'wechat_qr' && key !== 'store_images') {
        formDataToSend.append(key, formData[key] || '')
      }
    })

    // Add new images if selected
    if (newLogo.value) {
      formDataToSend.append('logo', newLogo.value)
    }

    if (newBanner.value) {
      formDataToSend.append('banner', newBanner.value)
    }

    if (newWechatQr.value) {
      formDataToSend.append('wechat_qr', newWechatQr.value)
    }

    newStoreImages.value.forEach(image => {
      formDataToSend.append('store_images', image)
    })

    await storeAPI.update(formDataToSend)
    ElMessage.success('Store settings updated successfully')
    
    // Reset file uploads
    newLogo.value = null
    newBanner.value = null
    newWechatQr.value = null
    newStoreImages.value = []
    logoFileList.value = []
    bannerFileList.value = []
    wechatQrFileList.value = []
    storeImagesFileList.value = []
    
    loadStoreInfo()
  } catch (error) {
    console.error('Failed to update store settings:', error)
  } finally {
    submitting.value = false
  }
}

onMounted(() => {
  loadStoreInfo()
})
</script>

<style lang="scss" scoped>
.page-header {
  margin-bottom: 2rem;

  h1 {
    margin: 0;
    color: var(--text-primary);
  }
}

:deep(.el-divider) {
  h3 {
    color: var(--text-primary);
    font-size: 1.125rem;
  }
}

.image-upload-section {
  width: 100%;
}

.store-images-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  gap: 1rem;
  margin-bottom: 1rem;
}
</style>

